import dash
from dash import dcc, html
import plotly.graph_objects as go
import pandas as pd
import json
import datetime

def calculate_metrics(df):
    # 计算日气耗评价值
    df['日气耗评价值'] = df['日气耗量 (m³)'] / df['面积 (m²)'] * 121
    return df
def calculate_metrics_1(df):
    # 计算日水耗评价值
    df['日水耗评价值'] = df['日水耗量 (m³)'] / df['面积 (m²)'] * 121
    return df

def add_heating_days(df):
    # 假设供暖开始日期为数据中最早的日期
    start_date = pd.to_datetime(df['日期']).min()

    # 假设当前日期为数据中最晚的日期
    end_date = pd.to_datetime(df['日期']).max()

    # 计算已供暖天数
    df['已供暖天数'] = (end_date - start_date).days + 1  # 包含开始和结束日期
    return df


# 加载数据
with open('data/供暖数据.json', 'r', encoding='utf-8') as f:
    data = json.load(f)

data_2025_05_22 = [item for item in data if item['日期'] == '2025-05-22']
df = pd.DataFrame(data_2025_05_22)
if '日气耗量 (m³)' in df.columns and '面积 (m²)' in df.columns:
    df = calculate_metrics(df)
else:
    raise KeyError("数据文件中缺少 '日气耗量 (m³)' 或 '面积 (m²)' 列")

if '日水耗量 (m³)' in df.columns and '面积 (m²)' in df.columns:
    df = calculate_metrics_1(df)
else:
    raise KeyError("数据文件中缺少 '日水耗量 (m³)' 或 '面积 (m²)' 列")

if '日期' in df.columns:
    df = add_heating_days(df)
else:
    raise KeyError("数据文件中缺少 '日期' 列")

# 初始化Dash应用
app = dash.Dash(__name__)

app.layout = html.Div(style={
    'background': '#f5f5f5',
    'minHeight': '100vh',
    'padding': '2rem',
    'fontFamily': 'Arial, sans-serif',
}, children=[
    # 标题区
    html.Div(style={
        'textAlign': 'center',
        'marginBottom': '3rem'
    }, children=[
        html.H1("🌡️ 智慧供暖数据展示", style={
            'color': '#333',
            'fontSize': '2.5rem',
            'marginBottom': '0.5rem'
        }),
        html.Div(style={
            'color': '#666',
            'fontSize': '1.2rem'
        }, children=[
            html.Span(f"日期：{df['日期'].values[0]}"),
            html.Span(" | "),
            html.Span(f"项目：{df['项目'].values[0]}"),
            html.Span(" | "),
            html.Span(f"集团：{df['集团'].values[0]}")
        ])
    ]),

    html.Div(style={
        'display': 'flex',
        'flexDirection': 'column',
        'gap': '1.5rem',
        'marginBottom': '2rem'
    }, children=[
        html.Div(style={
            'background': '#fff',
            'borderRadius': '8px',
            'padding': '1.5rem',
            'boxShadow': '0 4px 6px rgba(0,0,0,0.1)'
        }, children=[
            html.H3("🔥 气耗指标", style={
                'color': '#e74c3c',
                'borderBottom': '2px solid #e74c3c',
                'paddingBottom': '0.5rem',
                'marginBottom': '1rem'
            }),
            html.Div(style={
                'display': 'flex',
                'justifyContent': 'space-between',
                'marginBottom': '0.8rem'
            }, children=[
                html.Span(f"{df['日气耗量 (m³)'].values[0]:.1f} m³", style={
                    'fontSize': '1.2rem',
                    'fontWeight': 'bold',
                    'color': '#333'
                }),
                html.Span("当日消耗", style={
                    'color': '#666',
                    'opacity': 0.8
                })
            ]),
            html.Div(style={
                'display': 'flex',
                'justifyContent': 'space-between',
                'marginBottom': '0.8rem'
            }, children=[
                html.Span(f"{df['累计气耗量 (m³)'].values[0]:.0f} m³", style={
                    'fontSize': '1.2rem',
                    'fontWeight': 'bold',
                    'color': '#333'
                }),
                html.Span("累计消耗", style={
                    'color': '#666',
                    'opacity': 0.8
                })
            ]),
            html.Div(style={
                'display': 'flex',
                'justifyContent': 'space-between',
                'marginBottom': '0.8rem'
            }, children=[
                html.Span(f"{df['日气耗评价值'].values[0]:.1f} 分", style={
                    'fontSize': '1.2rem',
                    'fontWeight': 'bold',
                    'color': '#333'
                }),
                html.Span("当日评分", style={
                    'color': '#666',
                    'opacity': 0.8
                })

            ])
        ]),

        html.Div(style={
            'background': '#fff',
            'borderRadius': '8px',
            'padding': '1.5rem',
            'boxShadow': '0 4px 6px rgba(0,0,0,0.1)'
        }, children=[
            html.H3("💧 水耗指标", style={
                'color': '#3498db',
                'borderBottom': '2px solid #3498db',
                'paddingBottom': '0.5rem',
                'marginBottom': '1rem'
            }),
            html.Div(style={
                'display': 'flex',
                'justifyContent': 'space-between',
                'marginBottom': '0.8rem'
            }, children=[
                html.Span(f"{df['日水耗量 (m³)'].values[0]:.1f} m³", style={
                    'fontSize': '1.2rem',
                    'fontWeight': 'bold',
                    'color': '#333'
                }),
                html.Span("当日消耗", style={
                    'color': '#666',
                    'opacity': 0.8
                })
            ]),
            html.Div(style={
                'display': 'flex',
                'justifyContent': 'space-between',
                'marginBottom': '0.8rem'
            }, children=[
                html.Span(f"{df['累计水耗量 (m³)'].values[0]:.0f} m³", style={
                    'fontSize': '1.2rem',
                    'fontWeight': 'bold',
                    'color': '#333'
                }),
                html.Span("累计消耗", style={
                    'color': '#666',
                    'opacity': 0.8
                })
            ]),
            html.Div(style={
                'display': 'flex',
                'justifyContent': 'space-between',
                'marginBottom': '0.8rem'
            }, children=[
                html.Span(f"{df['日水耗评价值'].values[0]:.1f} 分", style={
                    'fontSize': '1.2rem',
                    'fontWeight': 'bold',
                    'color': '#333'
                }),
                html.Span("当日评分", style={
                    'color': '#666',
                    'opacity': 0.8
                })

            ])
        ]),

        html.Div(style={
            'background': '#fff',
            'borderRadius': '8px',
            'padding': '1.5rem',
            'boxShadow': '0 4px 6px rgba(0,0,0,0.1)'
        }, children=[
            html.H3("🌡️ 环境指标", style={
                'color': '#2ecc71',
                'borderBottom': '2px solid #2ecc71',
                'paddingBottom': '0.5rem',
                'marginBottom': '1rem'
            }),
            html.Div(style={
                'display': 'flex',
                'justifyContent': 'space-between',
                'marginBottom': '0.8rem'
            }, children=[
                html.Span(f"{df['室外温度 (°C)'].values[0]:.1f} °C", style={
                    'fontSize': '1.2rem',
                    'fontWeight': 'bold',
                    'color': '#333'
                }),
                html.Span("室外温度", style={
                    'color': '#666',
                    'opacity': 0.8
                })
            ]),
            html.Div(style={
                'display': 'flex',
                'justifyContent': 'space-between',
                'marginBottom': '0.8rem'
            }, children=[
                html.Span(f"{df['已供暖天数'].values[0]} 天", style={
                    'fontSize': '1.2rem',
                    'fontWeight': 'bold',
                    'color': '#333'
                }),
                html.Span("已供暖天数", style={
                    'color': '#666',
                    'opacity': 0.8
                })
            ]),
            html.Div(style={
                'display': 'flex',
                'justifyContent': 'space-between',
                'marginBottom': '0.8rem'
            }, children=[
                html.Span("0.79 元/m²", style={
                    'fontSize': '1.2rem',
                    'fontWeight': 'bold',
                    'color': '#333'
                }),
                html.Span("能耗成本", style={
                    'color': '#666',
                    'opacity': 0.8
                })
            ])
        ])
    ]),

    # 时间线展示区
    html.Div(style={
        'background': '#fff',
        'borderRadius': '8px',
        'padding': '1.5rem',
        'boxShadow': '0 4px 6px rgba(0,0,0,0.1)',
        'marginBottom': '2rem'
    }, children=[
        html.H3("⏳ 历史数据时间线", style={
            'color': '#9b59b6',
            'borderBottom': '2px solid #9b59b6',
            'paddingBottom': '0.5rem',
            'marginBottom': '1rem'
        }),
        dcc.Graph(
            figure=go.Figure(
                data=go.Scatter(
                    x=df['日期'],
                    y=df['日气耗量 (m³)'],
                    mode='lines+markers',
                    line=dict(color='#9b59b6'),
                    marker=dict(size=8)
                )
            ).update_layout(
                title="🔥 气耗变化历史",
                xaxis_title="日期",
                yaxis_title="消耗量 (m³)",
                plot_bgcolor='#fff',
                paper_bgcolor='#fff',
                font=dict(color='#333')
            )
        )
    ]),

    # 动态数据流展示区
    html.Div(style={
        'background': '#fff',
        'borderRadius': '8px',
        'padding': '1.5rem',
        'boxShadow': '0 4px 6px rgba(0,0,0,0.1)'
    }, children=[
        html.H3("📊 实时数据流", style={
            'color': '#f1c40f',
            'borderBottom': '2px solid #f1c40f',
            'paddingBottom': '0.5rem',
            'marginBottom': '1rem'
        }),
        html.Div(style={
            'display': 'flex',
            'justifyContent': 'space-between',
            'marginBottom': '0.8rem'
        }, children=[
            html.Span("🔥 实时气耗：", style={
                'fontSize': '1.2rem',
                'fontWeight': 'bold',
                'color': '#333'
            }),
            html.Span(f"{df['日气耗量 (m³)'].values[0]:.1f} m³", style={
                'fontSize': '1.2rem',
                'fontWeight': 'bold',
                'color': '#e74c3c'
            })
        ]),
        html.Div(style={
            'display': 'flex',
            'justifyContent': 'space-between',
            'marginBottom': '0.8rem'
        }, children=[
            html.Span("💧 实时水耗：", style={
                'fontSize': '1.2rem',
                'fontWeight': 'bold',
                'color': '#333'
            }),
            html.Span(f"{df['日水耗量 (m³)'].values[0]:.1f} m³", style={
                'fontSize': '1.2rem',
                'fontWeight': 'bold',
                'color': '#3498db'
            })
        ]),
        html.Div(style={
            'display': 'flex',
            'justifyContent': 'space-between',
            'marginBottom': '0.8rem'
        }, children=[
            html.Span("🌡️ 实时温度：", style={
                'fontSize': '1.2rem',
                'fontWeight': 'bold',
                'color': '#333'
            }),
            html.Span(f"{df['室外温度 (°C)'].values[0]:.1f} °C", style={
                'fontSize': '1.2rem',
                'fontWeight': 'bold',
                'color': '#2ecc71'
            })
        ])
    ])
])

if __name__ == '__main__':
    app.run(debug=True)
